package HashTable2;

import HashTable.HashBuck;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-07-05
 * Time: 9:47
 */
public class HashBuck2<K,V> {
    static class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;
        public Node(K key,V val){
            this.key=key;
            this.val=val;
        }
    }
    public Node<K,V>[] array=(Node<K, V>[]) new Node[10];
    public int usedSize;
    public static final double DEFAULT_LOAD_FACTOR=0.75;
    public void put(K key,V val){
        Node<K,V> node=new Node<>(key,val);
        int hash=key.hashCode();
        int index=hash% array.length;
        Node<K,V> cur=array[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                cur.val=val;
            }
            cur=cur.next;
        }
        node.next=array[index];
        array[index]=node;
        usedSize++;
        if(loadFactor()>=DEFAULT_LOAD_FACTOR){
            //扩容
            resize();
        }
    }
    private void resize(){
        Node<K,V>[] tmp=(Node<K, V>[]) new Node[2*array.length];
        for(int i=0;i<array.length;i++){
            Node<K,V>cur=array[i];
            while(cur!=null){
                Node<K,V> curNext=cur.next;
                int key=cur.key.hashCode();
                int index=key% tmp.length;
                cur.next=tmp[index];
                tmp[index]=cur;
                cur=curNext;
            }
        }
        array=tmp;
    }
    private double loadFactor(){
        return 1.0*usedSize/ array.length;
    }
    public V get(K key){
        int hash=key.hashCode();
        int index=hash%array.length;
        Node<K,V> cur=array[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                return cur.val;
            }
            cur=cur.next;
        }
        return null;
    }
}
